import { ReactElement, useRef, useEffect } from 'react'
import { Modal, Form, FormInstance, message, DatePicker } from 'antd'
import { ConfigSchema } from '../../ajax'
import UnitNumberInput from '@components/unitNumberInput'
import { updateConfigRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import moment from 'moment'

const { Item } = Form

async function submitHandle (d: { [k: string]: any }, hide: () => void, refreshData: () => void): Promise<void> {
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateConfigRequest(d))
  h()
  if (e === null) {
    message.success('更新成功').then(null, null)
    hide()
    refreshData()
  }
}

interface Props {
  visible: boolean
  data: ConfigSchema | null
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, data, hide, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {
    const c = formRef.current
    if (visible && data !== null && c !== null) {
      const d: { [k: string]: any } = { ...data }
      if (typeof d.effective_datetime === 'number') {
        d.effective_datetime = moment(d.effective_datetime * 1000)
      }
      c.setFieldsValue(d)
    } else if (!visible && c !== null) {
      c.resetFields()
    }
  }, [data, formRef, visible])
  return (
    <Modal title='编辑时限配置' visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={async d => await submitHandle(d, hide, refreshData)}>
        <Item name='id' noStyle><span /></Item>
        <Item label='答辩期' name='defence_period'>
          <UnitNumberInput placeholder='请输入' unit='天' />
        </Item>
        <Item label='审限' name='processing_period'>
          <UnitNumberInput placeholder='请输入' unit='天' />
        </Item>
        <Item label='生效日期' name='effective_datetime'>
          <DatePicker style={{ width: '100%' }} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
